"""
阿里云ECS参考资料：
    https://help.aliyun.com/document_detail/25506.htm?spm=a2c4g.11186623.2.38.7a662270xfdass#t9865.html
json:
    序列化的过程(dumps)：python object ------- json
    反序列化(loads):json----python object
"""

import json
import logging
import pprint

from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkecs.request.v20140526.ModifyInstanceAttributeRequest import ModifyInstanceAttributeRequest
from aliyunsdkecs.request.v20140526.RebootInstanceRequest import RebootInstanceRequest
from aliyunsdkecs.request.v20140526.StartInstanceRequest import StartInstanceRequest
from aliyunsdkecs.request.v20140526.StopInstanceRequest import StopInstanceRequest

from scan.models import Machine, Account
from sdk.ali.base import AliBase


class AliEcs(AliBase):
    def get_ecs(self):
        response = self.base(DescribeInstancesRequest)
        for ecs in response.get('Instances', {}).get('Instance'):
            attrs = [attr.attname for attr in Machine._meta.fields]
            MB2G = lambda x: x // 1024
            data_ecs = {attr: ecs.get(attr) for attr in attrs if attr in ecs}
            data_ecs['Memory'] = MB2G(data_ecs['Memory'])
            data_ecs['CreateMethod'] = 2
            data_ecs['OSType'] = 2 if data_ecs['OSType'] == 'linux' else 1
            data_ecs['PublicIpAddresses'] = ecs.get('PublicIpAddress', {}).get('IpAddress')
            # **data_ecs字典解包
            m, is_create = Machine.objects.update_or_create(**data_ecs,
                                                            defaults={'SerialNumber': ecs.get('SerialNumber')})
            if is_create:
                # 设置密码信息并入库存储
                Password = self.generate_password
                self.set_password(InstanceId=ecs.get('InstanceId'), Password=Password)
                Account.objects.update_or_create(User='root', Password=Password, Machine=m)
                self.reboot(InstanceId=ecs.get('InstanceId'))
                print('录入成功')

    # 需求：扫描到的机器没有密码
    def set_password(self, **kwargs):
        print('----', kwargs)
        kwargs = {
            'InstanceId': kwargs.get('InstanceId'),
            'Password': kwargs.get('Password')
        }
        return self.base(ModifyInstanceAttributeRequest, **kwargs)

    def reboot(self, **kwargs):
        kwargs = {
            'InstanceId': kwargs.get('InstanceId'),
            'ForceStop': kwargs.get('ForceStop', False)
        }
        return self.base(RebootInstanceRequest, **kwargs)

    def start(self, **kwargs):
        kwargs = {
            'InstanceId': kwargs.get('InstanceId'),
        }
        return self.base(StartInstanceRequest, **kwargs)

    def stop(self, **kwargs):
        kwargs = {
            'InstanceId': kwargs.get('InstanceId'),
        }
        return self.base(StopInstanceRequest, **kwargs)
